package org.jeecg.modules.solitaire_app.app.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.PageInfo;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.solitaire_app.app.entity.VO.ReceivingSealCarOrderVO;
import org.jeecg.modules.solitaire_app.app.entity.VO.SealCarOrderDetailVO;
import org.jeecg.modules.solitaire_app.app.entity.VO.YsySealCarOrderVO;
import org.jeecg.modules.solitaire_app.app.entity.YsySealCarOrder;
import org.jeecg.modules.solitaire_app.app.entity.YsyUsers;
import org.jeecg.modules.solitaire_app.app.query.AddSealCarOrderQuery;
import org.jeecg.modules.solitaire_app.app.query.ReceivingOrderListQuery;
import org.jeecg.modules.solitaire_app.app.query.SealCarOrderQuery;
import org.jeecg.modules.solitaire_app.app.query.UserSealCarOrderQuery;
import org.jeecg.modules.solitaire_app.app.service.IYsySealCarOrderService;

import java.util.Date;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.modules.solitaire_app.app.service.IYsyUsersService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * @Description: 封车订单表
 * @Author: jeecg-boot
 * @Date: 2023-08-29
 * @Version: V1.0
 */
@Slf4j
@Api(tags = "封车订单表")
@RestController
@RequestMapping("/app/ysySealCarOrder")
public class YsySealCarOrderController extends JeecgController<YsySealCarOrder, IYsySealCarOrderService> {
    @Autowired
    private IYsySealCarOrderService ysySealCarOrderService;
    @Autowired
    private IYsyUsersService ysyUsersService;

    /**
     * 分页列表查询
     *
     * @param ysySealCarOrder
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "封车订单表-分页列表查询")
    @ApiOperation(value = "封车订单表-分页列表查询", notes = "封车订单表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(YsySealCarOrder ysySealCarOrder,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {

        QueryWrapper<YsySealCarOrder> queryWrapper = QueryGenerator.initQueryWrapper(ysySealCarOrder, req.getParameterMap());
        pageSize = 30;
        Page<YsySealCarOrder> page = new Page<YsySealCarOrder>(pageNo, pageSize);
        IPage<YsySealCarOrder> pageList = ysySealCarOrderService.page(page, queryWrapper);
        // 获取当前时间的 Date 对象
        Date currentTime = new Date();

        // 获取一小时后的时间点的 Date 对象
        long oneHourInMillis = 60 * 60 * 1000; // 一小时的毫秒数
        Date oneHourLater = new Date(currentTime.getTime() + oneHourInMillis);
        pageList.getRecords().stream().forEach(item -> {
            if (item.getStatus() == 0 && item.getCreateTime().before(oneHourLater)) {
                item.setChaoShiFlag(1);
            } else {
                item.setChaoShiFlag(0);
            }

            if (item.getStatus() == 1 && item.getCreateTime().before(oneHourLater)) {
                item.setChaoShiFlag(1);
            } else {
                item.setChaoShiFlag(0);
            }

        });

        return Result.ok(pageList);
    }

    /**
     * 添加
     *
     * @param addSealCarOrderQuery
     * @return
     */
    @AutoLog(value = "封车订单表-添加")
    @ApiOperation(value = "封车订单表-添加", notes = "封车订单表-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody AddSealCarOrderQuery addSealCarOrderQuery) {
        return ysySealCarOrderService.addSealCarOrder(addSealCarOrderQuery);
    }

    /**
     * 添加
     *
     * @param addSealCarOrderQuery
     * @return
     */
    @AutoLog(value = "封车订单表-后台添加")
    @ApiOperation(value = "封车订单表-后台添加", notes = "封车订单表-后台添加")
    @PostMapping(value = "/adminAdd")
    public Result<?> adminAdd(@RequestBody AddSealCarOrderQuery addSealCarOrderQuery) {
        return ysySealCarOrderService.adminAdd(addSealCarOrderQuery);
    }

    /**
     * 我的封车订单
     *
     * @param userSealCarOrderQuery
     * @return
     */
    @AutoLog(value = "封车订单表-我的封车订单")
    @ApiOperation(value = "封车订单表-我的封车订单", notes = "封车订单表-我的封车订单")
    @PostMapping(value = "/getUserSealCarOrders")
    public Result<PageInfo<YsySealCarOrderVO>> getUserSealCarOrders(@RequestBody UserSealCarOrderQuery userSealCarOrderQuery) {
        return ysySealCarOrderService.getUserSealCarOrders(userSealCarOrderQuery);
    }

    /**
     * 封车订单详情
     *
     * @param orderId
     * @return
     */
    @AutoLog(value = "封车订单表-封车订单详情")
    @ApiOperation(value = "封车订单表-封车订单详情", notes = "封车订单表-封车订单详情")
    @GetMapping(value = "/getUserSealCarOrderDetail/{orderId}")
    public Result<SealCarOrderDetailVO> getUserSealCarOrderDetail(@PathVariable("orderId") String orderId) {
        return ysySealCarOrderService.getUserSealCarOrderDetail(orderId);
    }

    /**
     * 查询订单分类
     *
     * @param userId
     * @return
     */
    @AutoLog(value = "封车订单表-查询订单分类")
    @ApiOperation(value = "封车订单表-查询订单分类", notes = "封车订单表-查询订单分类")
    @GetMapping(value = "/getOrderType/{userId}")
    public Result<JSONArray> getOrderType(@PathVariable("userId") String userId) {
        return ysySealCarOrderService.getOrderType(userId);
    }

    /**
     * 任务列表
     *
     * @param sealCarOrderQuery
     * @return
     */
    @AutoLog(value = "封车订单表-任务列表（派单/转单/抢单）")
    @ApiOperation(value = "封车订单表-任务列表（派单/转单/抢单）", notes = "封车订单表-任务列表（派单/转单/抢单）")
    @PostMapping(value = "/getSealCarOrderList")
    public Result<PageInfo<YsySealCarOrderVO>> getSealCarOrderList(@RequestBody SealCarOrderQuery sealCarOrderQuery) {
        return ysySealCarOrderService.getSealCarOrderList(sealCarOrderQuery);
    }

    /**
     * 任务列表
     *
     * @param receivingOrderListQuery
     * @return
     */
    @AutoLog(value = "封车订单表-查询驻场用户接单的封车订单列表")
    @ApiOperation(value = "封车订单表-查询驻场用户接单的封车订单列表", notes = "封车订单表-查询驻场用户接单的封车订单列表")
    @PostMapping(value = "/getUserReceivingOrderList")
    public Result<PageInfo<ReceivingSealCarOrderVO>> getUserReceivingOrderList(@RequestBody ReceivingOrderListQuery receivingOrderListQuery) {
        return ysySealCarOrderService.getUserReceivingOrderList(receivingOrderListQuery);
    }

    /**
     * 接单
     *
     * @param userId,orderId
     * @return
     */
    @AutoLog(value = "封车订单表-接单")
    @ApiOperation(value = "封车订单表-接单", notes = "封车订单表-接单")
    @GetMapping(value = "/receivingOrder/{userId}/{orderId}")
    public Result<YsySealCarOrderVO> receivingOrder(@PathVariable("userId") String userId, @PathVariable("orderId") String orderId) {
        return ysySealCarOrderService.receivingOrder(userId, orderId);
    }

    /**
     * 接单
     *
     * @param userId,orderId
     * @return
     */
    @AutoLog(value = "封车订单表-接单后操作（2-赶往炼厂，3-已到达炼厂")
    @ApiOperation(value = "封车订单表-接单后操作（2-赶往炼厂，3-已到达炼厂", notes = "封车订单表-接单后操作（2-赶往炼厂，3-已到达炼厂")
    @GetMapping(value = "/receivingOrderUpdate/{userId}/{orderId}/{type}")
    public Result<YsySealCarOrderVO> receivingOrderUpdate(@PathVariable("userId") String userId, @PathVariable("orderId") String orderId, @PathVariable("type") int type) {
        return ysySealCarOrderService.receivingOrderUpdate(userId, orderId, type);
    }

    /**
     * 转单
     *
     * @param userId,orderId
     * @return
     */
    @AutoLog(value = "封车订单表-转单")
    @ApiOperation(value = "封车订单表-转单", notes = "封车订单表-转单")
    @GetMapping(value = "/transferOrder/{userId}/{orderId}/{transferUserId}")
    public Result<YsySealCarOrderVO> transferOrder(@PathVariable("userId") String userId, @PathVariable("orderId") String orderId, @PathVariable("transferUserId") String transferUserId) {
        return ysySealCarOrderService.transferOrder(userId, orderId, transferUserId);
    }

    /**
     * 编辑
     *
     * @param ysySealCarOrder
     * @return
     */
    @AutoLog(value = "封车订单表-编辑")
    @ApiOperation(value = "封车订单表-编辑", notes = "封车订单表-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody YsySealCarOrder ysySealCarOrder) {
        YsySealCarOrder ysySealCarOrderDB = ysySealCarOrderService.getById(ysySealCarOrder.getId());
        if (ObjectUtil.isNotEmpty(ysySealCarOrderDB) && ysySealCarOrder.getOrderType() == null) {
            //接单外的任务
            ysySealCarOrderService.updateById(ysySealCarOrder);
            return Result.ok("编辑成功!");
        }
        if (ObjectUtil.isNotEmpty(ysySealCarOrderDB)
                && ysySealCarOrder.getOrderType() != null
                && ysySealCarOrder.getOrderType() == 3) {
            //转单
            YsyUsers ysyUsers = ysyUsersService.getById(ysySealCarOrder.getTransferUserId());
            ysySealCarOrder.setTransferTime(new Date());
            ysySealCarOrder.setStatus(11);
            ysySealCarOrder.setTransferUserAvatar(ysyUsers.getAvatarUrl());
            ysySealCarOrder.setTransferUserName(ObjectUtil.isNotEmpty(ysyUsers.getRealName())
                    ? ysyUsers.getRealName()
                    : ysyUsers.getNickName());
            ysySealCarOrderService.updateById(ysySealCarOrder);
            return Result.ok("编辑成功!");
        } else {
            return null;
        }
    }

    public static void main(String[] args) {
        YsySealCarOrder ysySealCarOrderj = new YsySealCarOrder();
        ysySealCarOrderj.setStatus(1);
        System.out.println(ObjectUtil.isNull(ysySealCarOrderj));
        System.out.println(ObjectUtil.isEmpty(ysySealCarOrderj));
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "封车订单表-通过id删除")
    @ApiOperation(value = "封车订单表-通过id删除", notes = "封车订单表-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        ysySealCarOrderService.removeById(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "封车订单表-批量删除")
    @ApiOperation(value = "封车订单表-批量删除", notes = "封车订单表-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.ysySealCarOrderService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "封车订单表-通过id查询")
    @ApiOperation(value = "封车订单表-通过id查询", notes = "封车订单表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        YsySealCarOrder ysySealCarOrder = ysySealCarOrderService.getById(id);
        return Result.ok(ysySealCarOrder);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param ysySealCarOrder
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, YsySealCarOrder ysySealCarOrder) {
        return super.exportXls(request, ysySealCarOrder, YsySealCarOrder.class, "封车订单表");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, YsySealCarOrder.class);
    }

}
